package ServerOperation;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import Controllers.Notificator;
import Controllers.GenericToolsForController.RequestMainStatusEnum;
import Entity.Request;
import Entity.Worker;
import ICM_OCSF.Server;

import java.sql.Connection;
import java.sql.SQLException;

import com.mysql.jdbc.Statement;

public class DailyUpdates extends TimerTask implements Runnable
{
	private static final long DAY=86400000; // day in MilliSeconds  = 24*60*60*1000.
	private static final String exception="Exception";
	private Connection conn;
	private Server server;
	private Timer timer;	
	
	
	
    public DailyUpdates(Connection conn,Server server) {
		super();
		this.conn = conn;
		this.server = server;
		this.timer= new Timer();
		
		//Get milliseconds until midnight
		Calendar c = Calendar.getInstance();
        Date now = new Date();
        c.setTime(now);
        c.add(Calendar.DAY_OF_MONTH, 1);
        c.set(Calendar.HOUR, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        long howMany = (c.getTimeInMillis()-now.getTime());
        //howMany  =0;
		timer.schedule(this,howMany, DAY);
	}


	@Override
	public void run() 
	{
		System.out.println("daily");
	    if(server.isAlive())
	    {
			dailyUpdatesOfExceprionsRequests();
			dailyUpdatesOfReminders();
	    }
	}

	/**
	 * function that Search requests that the time of the current step
	 * About to over in one day. then send Reminder by Email to the  Responsible of this step.
	 * @return void
	 */
	private void dailyUpdatesOfReminders() 
	{
		List<Request> listOfRequest = 
				 GenricOperation.getAllRequestByMainStatus(RequestMainStatusEnum.OPEN.getText(), conn);
		// to all open requests check if the current time is bigger then the due time
		System.out.println("daily remineder");
		for (Request req : listOfRequest)
		 {
				if(req.getCurrentStatus().getDueDate() != null)
				{
					long days = req.getCurrentStatus().getDueDate().getTime() - (new Date()).getTime();
					if( days <= DAY &&  days >=0)
					{
						Worker responsibleStep=null;
						 String stepName = null;
						 if(req.isInEvluation()) 
						 {
							 responsibleStep = req.getEvaluator();
							 stepName = "Evluation";
						 }
						 else if(req.isInClose()) 
						 {
							 responsibleStep = req.getInspector();
							 stepName = "Close Request";
					     }
						 else if(req.isInExecuation()) 
						 {
							 responsibleStep = req.getExecutionLeader();
							 stepName = "Execuation";
						 }
						 else if(req.isInReviewAndDecision()) 
						 {
							 responsibleStep = req.getChairman();
							 stepName = "Review And Decision";
						 }
						 else if(req.isInTesting()) 
						 {
							 responsibleStep = req.getExaminer();
							 stepName = "Testing";
						 }
 
						 Notificator.sendEmailNotification(responsibleStep.getEmail(), "Attention, \n" +
								 		"you have one day to finish the handle of the " + stepName+ " step\n .\n" +
						 				"in Request number : " + req.getRequestId() + ". " +
						 				"If you not do so then you will exceed the time.");
						 	
					}
				}
		 }
		
	}


	/**
	 * function that Search requests that the time of the current step
	 * is over. then send Reminder by Email to:
	 * Responsible of this step.
	 * The inspector of this requests
	 * The ICM Manager
	 * @return void
	 */
	private void dailyUpdatesOfExceprionsRequests()
	{
		// the daily Updates is only to OPEN requests
		List<Request> listOfRequest = 
				 GenricOperation.getAllRequestByMainStatus(RequestMainStatusEnum.OPEN.getText(), conn);
		// to all open requests check if the current time is bigger then the due time
		for (Request req : listOfRequest)
		 {
				if(req.getCurrentStatus().getDueDate() != null)
				{
					long days = req.getCurrentStatus().getDueDate().getTime() - (new Date()).getTime();
					if( days < 0 )
					{
						 String comment = req.getCurrentStatus().getComment();
						 if(comment.startsWith(exception) == false) // if this is the first time that the request been view "Exception Request:
						 {
							 if(comment.startsWith(exception) == false) // if this is the first time that the request been view "Exception Request:
							 {
								String SpecficQuery = new String("Update history " +
											                         " set Comment = '"  + exception + ": " +req.getCurrentStatus().getComment() + 
											                         "' WHERE id = "+ req.getCurrentStatus().getHistoryId()+"");
								try 
								{
								   System.out.println(SpecficQuery);
									java.sql.Statement stmt = conn.createStatement();
									stmt.executeUpdate(SpecficQuery);
									stmt.close();
								}
								catch (SQLException e) 
								{
									e.printStackTrace();
								}
								 
							 }
							 
						 }
							 Worker responsibleStep=null,inspector=null,icmManager=null;
							 String stepName = null;
							 if(req.isInEvluation()) 
							 {
								 responsibleStep = req.getEvaluator();
								 stepName = "Evluation";
							 }
							 else if(req.isInClose()) 
							 {
								 responsibleStep = req.getInspector();
								 stepName = "Close Request";
						     }
							 else if(req.isInExecuation()) 
							 {
								 responsibleStep = req.getExecutionLeader();
								 stepName = "Execuation";
							 }
							 else if(req.isInReviewAndDecision()) 
							 {
								 responsibleStep = req.getChairman();
								 stepName = "Review And Decision";
							 }
							 else if(req.isInTesting()) 
							 {
								 responsibleStep = req.getExaminer();
								 stepName = "Testing";
							 }
							 inspector = req.getInspector();
							 icmManager =  GenricOperation.getIcmManager(conn);
							 
							 Notificator.sendEmailNotification(responsibleStep.getEmail(), "Attention, \n" +
									 		"you have exceeded the time that you had to preform action.\n" +
							 				"in the " + stepName+ " step\n" +
							 				"Request number : " + req.getRequestId() + ".");
							 
							 Notificator.sendEmailNotification(inspector.getEmail(), "Attention, \n" +
							 "The Requset number " + req.getRequestId() + "is exceeded the time of " + stepName + "\n" +
									 "The Responsible worker for this step is:\n" +
									 "Name: " + responsibleStep.getFirstName() + " " + responsibleStep.getLastName() + "\n" + 
									 "Worker Id : " + responsibleStep.getId());
							 
							 Notificator.sendEmailNotification(icmManager.getEmail(), "Attention, \n" +
									 "The Requset number " + req.getRequestId() + "is exceeded the time of " + stepName + "\n" +
											 "The Responsible worker for this step is:\n" +
											 "Name: " + responsibleStep.getFirstName() + " " + responsibleStep.getLastName() + "\n" + 
											 "Worker Id : " + responsibleStep.getId());
							 
					}
				}		
		 }
	}
	
}
 
